//
//  LoginTypeSelectViewController.m
//  ShrimpCrowdordering
//
//  Created by 郑洲 on 2018/7/26.
//  Copyright © 2018年 郑洲. All rights reserved.
//

#import "LoginTypeSelectViewController.h"

#import "LoginViewController.h"

#import <TencentOpenAPI/QQApiInterface.h>
#import <TencentOpenAPI/TencentOAuth.h>
#import "WXApi.h"

@interface LoginTypeSelectViewController ()<TencentSessionDelegate>

@property (nonatomic,strong) TencentOAuth *tencentOAuth;
@property (nonatomic,strong) NSMutableArray *permissionArray;   //权限列表

@end

@implementation LoginTypeSelectViewController
- (void)viewWillAppear:(BOOL)animated {
    [super viewWillAppear:animated];
    self.navigationController.navigationBarHidden = YES;
}

- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view.
    self.view.backgroundColor = [UIColor whiteColor];
    [self setUI];
}

- (void)setUI {
    UIImageView *bgView = [[UIImageView alloc] initWithFrame:CGRectMake(0, 0, SCREEN_WIDTH, SCREEN_HEIGHT)];
    bgView.image = ImageWithName(@"图层11");
    bgView.clipsToBounds = YES;
    bgView.contentMode = UIViewContentModeScaleAspectFill;
    [self.view addSubview:bgView];
    
    UILabel *noteLabel = [[UILabel alloc] initWithFrame:CGRectMake(0, ScreenX375(255), SCREEN_WIDTH, ScreenX375(28))];
    noteLabel.text = @"设计是一种态度";
    noteLabel.textAlignment = NSTextAlignmentCenter;
    noteLabel.font = Kfont(23);
    noteLabel.textColor = REXADECIMALCOLOR(@"#000000");
    [self.view addSubview:noteLabel];
    
    UILabel *selectNote = [[UILabel alloc] initWithFrame:CGRectMake((SCREEN_WIDTH - ScreenX375(100)) / 2, ScreenX375(520), ScreenX375(100), ScreenX375(50))];
    selectNote.text = @"选择登录";
    selectNote.textAlignment = NSTextAlignmentCenter;
    selectNote.font = Kfont(14);
    selectNote.textColor = REXADECIMALCOLOR(@"#000000");
    [self.view addSubview:selectNote];
    
    NSMutableArray *btnArr = [NSMutableArray arrayWithObject:@"手机"];
//    if ([WXApi isWXAppInstalled]) {
        [btnArr addObject:@"微信"];
//    }
//    if ([QQApiInterface isQQInstalled]) {
        [btnArr addObject:@"QQ"];
//    }
    CGFloat margin = (SCREEN_WIDTH - btnArr.count * ScreenX375(50)) / (btnArr.count + 1);
    for (int i = 0; i < btnArr.count; i++) {
        UIButton *loginBtn = [[UIButton alloc] initWithFrame:CGRectMake((i + 1) * margin + i * ScreenX375(50), ScreenX375(580), ScreenX375(50), ScreenX375(50))];
        [loginBtn setTitle:btnArr[i] forState:UIControlStateNormal];
        [loginBtn setTitleColor:REXADECIMALCOLOR(@"#000000") forState:UIControlStateNormal];
        [loginBtn setImage:[UIImage imageNamed:btnArr[i]] forState:UIControlStateNormal];
        loginBtn.titleLabel.font = Kfont(10);
        
        CGSize imgViewSize,titleSize,btnSize;
        UIEdgeInsets imageViewEdge,titleEdge;
        CGFloat heightSpace = 10.0f;
        
        //设置按钮内边距
        imgViewSize = loginBtn.imageView.bounds.size;
        titleSize = loginBtn.titleLabel.bounds.size;
        btnSize = loginBtn.bounds.size;
        imageViewEdge = UIEdgeInsetsMake(0,0.0, btnSize.height -imgViewSize.height - heightSpace, - titleSize.width);
        titleEdge = UIEdgeInsetsMake(30, - imgViewSize.width, 0.0, 0.0);
        [loginBtn setImageEdgeInsets:imageViewEdge];
        [loginBtn setTitleEdgeInsets:titleEdge];
        [loginBtn addTarget:self action:@selector(loginClick:) forControlEvents:UIControlEventTouchUpInside];
        [self.view addSubview:loginBtn];
    }
}

- (void)loginClick:(UIButton *)button {
    if ([button.titleLabel.text isEqualToString:@"手机"]) {
        LoginViewController *vc = [[LoginViewController alloc] init];
        [self.navigationController pushViewController:vc animated:YES];
    }else if ([button.titleLabel.text isEqualToString:@"QQ"]) {
        ///QQ登录
        self.tencentOAuth = [[TencentOAuth alloc] initWithAppId:kQQAppKey andDelegate:self];
        //设置权限数据 ， 具体的权限名，在sdkdef.h 文件中查看。
        _permissionArray = [NSMutableArray arrayWithObjects: kOPEN_PERMISSION_GET_SIMPLE_USER_INFO,kOPEN_PERMISSION_GET_INFO,kOPEN_PERMISSION_GET_USER_INFO,nil];
        //登录操作
        [_tencentOAuth authorize:_permissionArray inSafari:NO];
    }else if ([button.titleLabel.text isEqualToString:@"微信"]) {
        ///微信登录
        //构造SendAuthReq结构体
        SendAuthReq* req =[[SendAuthReq alloc ] init];
        req.scope = @"snsapi_userinfo" ;
        req.state = @"123" ;
        //第三方向微信终端发送一个SendAuthReq消息结构
        [WXApi sendReq:req];
    }
}

#pragma mark - 微信登录
- (void)wechatLogin:(NSNotification *)aNotification{
    NSString *code = aNotification.object[@"code"];
    
//    [HttpManager showWait];
//    [HttpManager postHttpRequestByGet:@"https://api.weixin.qq.com/sns/oauth2/access_token" andParameter:@{@"appid":kWechatAppId,@"secret":kWechatSecret,@"code":code,@"grant_type":@"authorization_code"} success:^(id successResponse) {
//        [HttpManager hideWait];
//        self.openType = @"0";
//        self.openId = [NSString stringWithFormat:@"%@",successResponse[@"openid"]];
//
//        [self getWechatUserinfo:[NSString stringWithFormat:@"%@",successResponse[@"access_token"]]];
//    } andFailure:^(id failureResponse) {
//        [HttpManager showFail];
//    }];
}

- (void)getWechatUserinfo:(NSString *)accessToken{
//    [HttpManager showWait];
//    [HttpManager postHttpRequestByGet:@"https://api.weixin.qq.com/sns/userinfo" andParameter:@{@"access_token":accessToken,@"openid":self.openId} success:^(id successResponse) {
//        [DGHttpPostManager hideWait];
//
//        self.headUrl = [NSString stringWithFormat:@"%@",successResponse[@"headimgurl"]];
//        self.userName = [NSString stringWithFormat:@"%@",successResponse[@"nickname"]];
//
//        [self thirdLoginAction];
//    } andFailure:^(id failureResponse) {
//        [HttpManager showFail];
//    }];
}

#pragma mark - QQ登录回调代理TencentSessionDelegate
- (void)tencentDidLogin
{
    if (_tencentOAuth.accessToken && 0 != [_tencentOAuth.accessToken length])
    {
        //  记录登录用户的OpenID、Token以及过期时间
        //_tencentOAuth.accessToken;
        //        NSLog(@"%@,%@",[_tencentOAuth accessToken],[_tencentOAuth openId]);
//        self.openType = @"1";
//        self.openId = [_tencentOAuth openId];
//        [_tencentOAuth getUserInfo];
    }
}

-(void)tencentDidNotLogin:(BOOL)cancelled
{
    if (cancelled)
    {
        [HttpManager showNoteMsg:@"用户取消登录"];
    }
    else
    {
        [HttpManager showNoteMsg:@"登录失败"];
    }
}

-(void)tencentDidNotNetWork
{
    [HttpManager showFail];
}

- (void)getUserInfoResponse:(APIResponse*) response {
    if (URLREQUEST_SUCCEED == response.retCode
        && kOpenSDKErrorSuccess == response.detailRetCode) {
//        self.headUrl = [response.jsonResponse valueForKey:@"figureurl_qq_1"];
//        self.userName = [response.jsonResponse valueForKey:@"nickname"];
//
//        [self thirdLoginAction];
    } else {
        [HttpManager showNoteMsg:@"操作失败请稍后再试"];
    }
}


- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
